package com.probox.common.entity.service.product.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.CustomerGroupTypeEnum;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.ProductOptType;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.product.ProductInfo;
import com.probox.common.entity.domain.product.ProductOperationDetail;
import com.probox.common.entity.domain.product.vo.ProductInfoQuery;
import com.probox.common.entity.domain.product.vo.ProductOperationDetailVo;
import com.probox.common.entity.mapper.product.ProductOperationDetailMapper;
import com.probox.common.entity.service.customer.ICustomerInfoService;
import com.probox.common.entity.service.product.IProductCountService;
import com.probox.common.entity.service.product.IProductInfoService;
import com.probox.common.entity.service.product.IProductOperationDetailService;
import com.probox.common.entity.service.product.IProductUnitService;
import com.probox.common.redis.service.RedisService;
import com.probox.customer.api.domain.CustomerGroupDefinitionQuery;
import com.probox.product.api.domain.ProductOptVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 用户行为日志Service业务层处理
 *
 * @date 2021-05-28
 */
@Service
@Transactional
public class ProductOperationDetailServiceImpl extends ServiceImpl<ProductOperationDetailMapper, ProductOperationDetail> implements IProductOperationDetailService {
    @Autowired
    private ProductOperationDetailMapper productOperationDetailMapper;

    @Autowired
    private IProductInfoService iProductInfoService;

    @Autowired
    private IProductCountService iProductCountService;

    @Autowired
    private IProductUnitService iProductUnitService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ICustomerInfoService iCustomerInfoService;

    private static final Logger logger = LoggerFactory.getLogger(ProductOperationDetailServiceImpl.class);



    /**
     * 查询我的分享列表
     *
     * @param query
     * @return
     */
    @Override
    public List<HashMap> queryList(ProductInfoQuery query) {
        List<HashMap> list = new ArrayList<>();
        QueryWrapper<ProductOperationDetail> queryWrapper = Wrappers.query();
        if (ObjectUtil.isNotEmpty(SecurityUtils.getCustomerUid())) {
            queryWrapper.eq("MEMBER_UID", SecurityUtils.getCustomerUid());
        } else throw new ProductException("当前用户有问题！");
        if (ObjectUtil.isNotEmpty(SecurityUtils.getCustomerPlatformUid())) {
            queryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        }
        if (ObjectUtil.isNotEmpty(query.getStartTime())) queryWrapper.ge("CREATE_TIME", query.getStartTime());
        if (ObjectUtil.isNotEmpty(query.getEndTime())) queryWrapper.le("CREATE_TIME", query.getEndTime());
        queryWrapper.eq("OPT_TYPE", ProductOptType.share.getKey());
        List<ProductOperationDetail> productOperationDetails = productOperationDetailMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(productOperationDetails)) return null;
        HashMap hashMap = new HashMap();
        productOperationDetails.forEach(vo -> {
            HashMap map = new HashMap();
            map.put("uid", vo.getProductUid());
            hashMap.put(vo.getProductUid(), vo.getCreateTime());
            list.add(map);
        });
        if (ObjectUtil.isNotEmpty(hashMap)) {
            list.add(hashMap);
        }
        return list;
    }

    /**
     * 用户行为日志,商品详情页
     *
     * @param productUid
     * @return
     */
    @Override
    public List<ProductOperationDetailVo> getOptList(Long productUid) {
        String key = CachePrefix.PRODUCT_OPT_BEHAVIOR + productUid;
        List<ProductOperationDetailVo> voList = redisService.getCacheList(key);
        if (ObjectUtil.isEmpty(voList)) {
            voList = new ArrayList<>();
            HashMap map = new HashMap();
            map.put("productUid", productUid);
            String date = DateUtils.getDate();
            map.put("end", date + " 23:59:59");
            Date yestDate = DateUtils.addDay(DateUtil.date(), -1);
            String s = DateUtils.dateTime(yestDate);
            map.put("start", s);
            List<ProductOperationDetail> optList = productOperationDetailMapper.getOptList(map);
            if (ObjectUtil.isEmpty(optList)) return voList;
            DateTime dateTime = DateUtil.parseDateTime(date + " 00:00:00");
            for (ProductOperationDetail detail : optList) {
                ProductOperationDetailVo vo = new ProductOperationDetailVo();
                BeanUtils.copyProperties(detail, vo);
                DateTime date1 = DateUtil.date(vo.getCreateTime());
                if (dateTime.compareTo(date1) >= 0) vo.setTime("一天前");
                else vo.setTime("今天");
                if(ObjectUtil.isEmpty(vo.getMemberHeadImg())){
                    vo.setMemberNickName("游客");
                }
                voList.add(vo);
            }
            redisService.setCacheList(key, voList);
            redisService.expire(key,10L,TimeUnit.MINUTES);
        }
        return voList;
    }

    /**
     * 查看首页的购买行为
     *
     * @return
     */
    @Override
    public List<ProductOperationDetailVo> getOptBuyList() {
        String key = CachePrefix.PLATFORM_OPT_BEHAVIOR + SecurityUtils.getCustomerPlatformUid();
        List<ProductOperationDetailVo> voList = redisService.getCacheList(key);
        if (ObjectUtil.isEmpty(voList)) {
            voList = new ArrayList<>();
            HashMap map = new HashMap();
            map.put("platformUid", SecurityUtils.getCustomerPlatformUid());
            String date = DateUtils.getDate();
            map.put("end", date + " 23:59:59");
            Date yestDate = DateUtils.addDay(DateUtil.date(), -1);
            String s = DateUtils.dateTime(yestDate);
            map.put("start", s);
            List<ProductOperationDetail> optList = productOperationDetailMapper.getOptBuyList(map);
            if (ObjectUtil.isEmpty(optList)) return voList;
            DateTime dateTime = DateUtil.parseDateTime(date + " 00:00:00");
            for (ProductOperationDetail detail : optList) {
                ProductOperationDetailVo vo = new ProductOperationDetailVo();
                BeanUtils.copyProperties(detail, vo);
                if (dateTime.compareTo(vo.getCreateTime()) >= 0) vo.setTime("一天前");
                else vo.setTime("今天");
                if(ObjectUtil.isEmpty(vo.getMemberHeadImg())){
                    vo.setMemberNickName("游客");
                }
                vo.setUnitName(iProductUnitService.getUnitName(detail.getProductUid()));
                voList.add(vo);
            }
            redisService.setCacheList(key, voList);
            redisService.expire(key,10L,TimeUnit.MINUTES);
        }
        return voList;
    }


    /**
     * 查询用户行为日志
     *
     * @param detailUid 用户行为日志ID
     * @return 用户行为日志
     */
    @Override
    public ProductOperationDetail selectProductOperationDetailById(Long detailUid) {
        return this.getById(detailUid);
    }

    /**
     * 查询用户行为日志列表
     *
     * @param productOperationDetail 用户行为日志
     * @return 用户行为日志
     */
    @Override
    public List<ProductOperationDetail> queryList(ProductOperationDetail productOperationDetail) {
        QueryWrapper<ProductOperationDetail> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getDetailUid())) && productOperationDetail.getDetailUid() != null) {
            queryWrapper.eq("detail_uid", productOperationDetail.getDetailUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getProductUid())) && productOperationDetail.getProductUid() != null) {
            queryWrapper.eq("product_uid", productOperationDetail.getProductUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getProductName())) && productOperationDetail.getProductName() != null) {
            queryWrapper.eq("product_name", productOperationDetail.getProductName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getProductUrl())) && productOperationDetail.getProductUrl() != null) {
            queryWrapper.eq("product_url", productOperationDetail.getProductUrl());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getOptType())) && productOperationDetail.getOptType() != null) {
            queryWrapper.eq("opt_type", productOperationDetail.getOptType());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getObjNumber())) && productOperationDetail.getObjNumber() != null) {
            queryWrapper.eq("obj_number", productOperationDetail.getObjNumber());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getMemberUid())) && productOperationDetail.getMemberUid() != null) {
            queryWrapper.eq("member_uid", productOperationDetail.getMemberUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getMemberNickName())) && productOperationDetail.getMemberNickName() != null) {
            queryWrapper.eq("member_nick_name", productOperationDetail.getMemberNickName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getMemberHeadImg())) && productOperationDetail.getMemberHeadImg() != null) {
            queryWrapper.eq("member_head_img", productOperationDetail.getMemberHeadImg());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productOperationDetail.getPlatformUid())) && productOperationDetail.getPlatformUid() != null) {
            queryWrapper.eq("platform_uid", productOperationDetail.getPlatformUid());
        }
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        return productOperationDetailMapper.selectList(queryWrapper);
    }

    /**
     * 新增用户行为日志
     *
     * @param productOperationDetail 用户行为日志
     * @return 结果
     */
    @Override
    public boolean insertProductOperationDetail(ProductOperationDetail productOperationDetail) {
        return this.save(productOperationDetail);
    }

    /**
     * 添加分享详情
     *
     * @param productUid
     */
    @Override
    public void save(Long productUid) {
        ProductInfo pro = iProductInfoService.getPro(productUid);
        if (ObjectUtil.isEmpty(pro)) throw new ProductException("商品信息不存在！");
        ProductOperationDetail operationDetail = new ProductOperationDetail();
        operationDetail.setCreateTime(DateUtil.date());
        operationDetail.setProductUid(productUid);
        operationDetail.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
        operationDetail.setObjNumber(1);

        operationDetail.setProductName(pro.getProductName());
        operationDetail.setOptType(ProductOptType.share.getKey());
        HashMap map = iCustomerInfoService.getCustomerInfoDetail(SecurityUtils.getCustomerUid());
        if (ObjectUtil.isEmpty(map)) throw new BaseException("用户信息不存在！");
        operationDetail.setMemberNickName(map.get("customerName").toString());
        if (ObjectUtil.isNotEmpty(map.get("headImage"))) {
            operationDetail.setMemberHeadImg(map.get("headImage").toString());
        }
        operationDetail.setMemberUid(SecurityUtils.getCustomerUid());
        this.save(operationDetail);
        //iProductCountService.incrBarterNumCount(productUid, 1l);
    }

    /**
     * 修改用户行为日志
     *
     * @param productOperationDetail 用户行为日志
     * @return 结果
     */
    @Override
    public boolean updateProductOperationDetail(ProductOperationDetail productOperationDetail) {

        return this.updateById(productOperationDetail);
    }

    /**
     * 批量删除用户行为日志
     *
     * @param detailUids 需要删除的用户行为日志ID
     * @return 结果
     */
    @Override
    public boolean deleteProductOperationDetailByIds(Long[] detailUids) {
        return this.removeByIds(Arrays.asList(detailUids));
    }

    /**
     * 获取入群信息
     * @param query
     * @return
     */
    @Override
    public List<ProductOptVo> getMemberUid(CustomerGroupDefinitionQuery query){
        Date startTime = query.getBeginTime();
        Date endTime = query.getEndTime();
        List<ProductOptVo> list = new ArrayList<>();
        QueryWrapper<ProductOperationDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("distinct MEMBER_UID");
        queryWrapper.eq("PLATFORM_UID",query.getPlatformId());
        if(CustomerGroupTypeEnum.shopHaveBuy.getKey().equals(query.getDefinitionType()))
            queryWrapper.eq("OPT_TYPE",ProductOptType.buy.getKey());
        if(CustomerGroupTypeEnum.shopHaveAddBuy.getKey().equals(query.getDefinitionType()))
            queryWrapper.eq("OPT_TYPE",ProductOptType.addCar.getKey());
        if(CustomerGroupTypeEnum.shopHavePlaceOrder.getKey().equals(query.getDefinitionType())){
            String [] array = {ProductOptType.buy.getKey(),ProductOptType.buy.getKey()};
            queryWrapper.in("OPT_TYPE",array);
        }
        if(ObjectUtil.isNotEmpty(startTime)){
            queryWrapper.ge("CREATE_TIME",startTime);
        }
        if(ObjectUtil.isNotEmpty(startTime)){
            queryWrapper.le("CREATE_TIME",endTime);
        }
        queryWrapper.ne("member_uid",0);
        List<ProductOperationDetail> productOperationDetails = productOperationDetailMapper.selectList(queryWrapper);
        if(ObjectUtil.isEmpty(productOperationDetails)) return list;
        productOperationDetails.forEach(opt -> list.add(new ProductOptVo(opt.getMemberUid())));
        return list;
    }
}
